package com.share.servlet;


import com.share.domain.UserDomain;
import com.share.domain.UserDomainImpl;
import com.share.entity.User;
import com.share.servlet.utils.ForwardUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by leep on 2015-12-29.
 */
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		RequestDispatcher rd = getServletContext().getRequestDispatcher("/login/login.jsp");
		rd.forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		UserDomain userDomain = new UserDomainImpl();
		User user = userDomain.getUserByName(userName);
		HttpSession session = req.getSession();
		String url = "/user";
		if (user == null) {
			url = "/login/login.jsp";
			req.setAttribute("errorMsg", "用户帐号不存在!");
		} else {
			if (!StringUtils.equals(user.getPassword(), password)) {
				url = "/login/login.jsp";
				req.setAttribute("errorMsg", "用户密码错!");
			} else {
				session.setAttribute("user", user);
				resp.sendRedirect(url);
				return;
			}
		}

		ForwardUtils.forward(req, resp, url, getServletContext());
	}
}
